<template>
    <div class="app-container">
        <el-form :model="queryParameters" :inline="true" label-width="68px">
            <el-form-item style="width:320px">
                <div>箱号:</div>
                <MultipleBoxNumbersDialog v-model="queryParameters.containerNo" />
            </el-form-item>
            <el-form-item style="width:240px">
                <div>订单号:</div>
                <el-input v-model.trim="queryParameters.orderNo" clearable placeholder="请输入"> </el-input>
            </el-form-item>
            <el-form-item style="width:300px">
                <div>提箱日期:</div>
                <el-date-picker v-model="queryParameters.outDate" clearable type="daterange" range-separator="~" start-placeholder="开始日期"
                end-placeholder="结束日期" />
            </el-form-item>
            <el-form-item style="width:300px">
                <div>客户</div>
                <el-input v-model="queryParameters.agentName" clearable placeholder="请输入"> </el-input>
            </el-form-item>
            <el-form-item style="width:300px">
                <div>还箱日期:</div>
                <el-date-picker v-model="queryParameters.returnDate" clearable type="daterange" range-separator="~" start-placeholder="开始日期"
                end-placeholder="结束日期" />
            </el-form-item>
            <el-form-item style="width:300px">
                <div>支付状态:</div>
                <el-select v-model="queryParameters.rentStatus" clearable placeholder="请选择">
                    <el-option label="未收" value="5"> </el-option>
                    <el-option label="已收" value="10"> </el-option>
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button @click="resetQueryParam" :icon="Refresh" style="margin-top: 30px">重置</el-button>
                <el-button @click="getTableData" :icon="Search" type="primary" style="margin-top: 30px">查询</el-button>
            </el-form-item>
        </el-form>
        <el-row align="middle"> 
            <el-col :span="1" :class="{'cursor':true, 'select-style': isActive1}" @click="checkStatus('')">全部</el-col>
            <el-col :span="1" :class="{'cursor':true, 'select-style': isActive2}" @click="checkStatus(5)">未还</el-col>
            <el-col :span="1" :class="{'cursor':true, 'select-style': isActive3}" @click="checkStatus(10)">已还</el-col>
            <el-col :span="18"></el-col>
            <el-col :span="1">  
                <el-tooltip effect="dark" content="此按钮可选择当前页及后续页所有集装箱" placement="left">
                    <template v-if="isSelectAll">
                        <el-button :icon="Finished" size="small" @click="slectAll" plain class="operatingArea">全选</el-button>
                    </template>
                    <template v-else>
                        <el-button size="small" @click="deselectAll" plain class="operatingArea">取消全选</el-button>
                    </template>
                </el-tooltip>
            </el-col>
            <el-col :span="1" class="cursor"> <el-button type="primary" size="small" @click="toCollect">收取</el-button></el-col>
            <el-col :span="1" class="cursor"><el-button @click="exportExcel" size="small"><el-icon><Document /></el-icon>导出</el-button></el-col>
        </el-row>
        <Table ref="tableRef" v-bind="table"  @pageChange="onTablePageChange" :allId="allId" :isAllCheck="isAllCheck"  @updateSelectAll="updateSelectAll" :disableHeaderCheckbox="disableHeaderCheckbox"></Table>
    </div>
</template>
<script lang="ts" setup>
import MultipleBoxNumbersDialog from '@/components/dialog/multipleBoxNumbersDialog'
import Table from '@/components/table'
import {onActivated, reactive, ref} from 'vue'
import { boxRentOrderDetentionChargePage, paymentBoxRentOrderDetentionCharge, exportBoxReturnBoxListDetail } from '@/api/orderManage/index'
import { downloadFile } from '@/utils/download'
import { Refresh, Search } from '@element-plus/icons-vue'
import {ElMessageBox, ElMessage } from 'element-plus'

import {formatContainerNo} from '@/utils/mlpBox' // 格式化箱号
const queryParameters = reactive({ // 查询相关参数
    containerNo: '',
    orderNo:'',
    payNo: '',
    outDate: '',
    returnDate: '',
    agentName: '',
    rentStatus:'',
    status:""
})
const param = reactive({
    pageNum: 1,
    pageSize: 10
})

onActivated(() => {
 getTableData()
})

const table = reactive({
    // 列表数据（必传）
    data: [],
    header: [
        { key: 'containerNo', colWidth: '100', title: '箱号', type: 'text', isCheck: true },
        { key: 'boxType', colWidth: '80', title: '箱型', type: 'filter', filter: { 5: '40HQ', 10: '40GP', 15: '20HQ', 20: '20GP' }, isCheck: true },
        { key: 'agentName', colWidth: '150', title: '客户', type: 'text', isCheck: true },
        { key: 'outDate', colWidth: '100', title: '提箱日期', type: 'date', isCheck: true },
        { key: 'returnDate', colWidth: '100', title: '还箱日期', type: 'date', isCheck: true },
        { key: 'returnCityName', colWidth: '80', title: '还箱城市', type: 'text', isCheck: true },
        { key: 'useDays', colWidth: '60', title: '租箱天数', type: 'add', after: '天', isCheck: true },
        { key: 'overdueDays', colWidth: '60', title: '超期天数', type: 'add', after: '天', isCheck: true },
        { key: 'overdueAmount', colWidth: '60', title: '超期费($)', type: 'add', currency: 'priceCurrency', isCheck: true },
        { key: 'status', colWidth: '60', title: '箱状态', type: 'filter', filter: { 5: '未还', 10: '已还'}, isCheck: true },
        { key: 'rentStatus', colWidth: '60', title: '支付状态', type: 'filter', filter: { 5: '未收', 10: '已收'}, isCheck: true },
        { key: 'orderNo', colWidth: '200', title: '订单号', type: 'text', isCheck: true },
    ],
     // table配置项（必传）
    config: {
        isSelection: true,
        isList: false,
        isPagination: true, // 是否分页
        total: 0, // 分页总数
        loading: false
    }   
})

const getTableData = () => { // 查询列表数据
    const { container, containerList } = formatContainerNo(queryParameters.containerNo);
    let reqParameters = {
        pageNum: param.pageNum,
        pageSize: param.pageSize,
        containerNo: container,
        containerNos: containerList,
        orderNo:queryParameters.orderNo,
        beginPlanPickupDate:"",
        endPlanPickupDate:"",
        agentName: queryParameters.agentName.trim(),
        beginReturnDate:"",
        endReturnDate:"",
        rentStatus: queryParameters.rentStatus,
        status:queryParameters.status
    }
    if(queryParameters.outDate){
        reqParameters.beginPlanPickupDate = queryParameters.outDate[0]
        reqParameters.endPlanPickupDate = queryParameters.outDate[1]
    }
    if(queryParameters.returnDate){
        reqParameters.beginReturnDate = queryParameters.returnDate[0]
        reqParameters.endReturnDate = queryParameters.returnDate[1]
    }
    boxRentOrderDetentionChargePage(JSON.stringify(reqParameters)).then((res: any) => {
        table.data = res.data.list
        table.config.total = res.data.total
    })
}
const isActive1 = ref(true)
const isActive2 = ref(false)
const isActive3 = ref(false)
const checkStatus = (status: any) => {
    switch (status) {
        case '':
            isActive1.value = true
            isActive2.value = false
            isActive3.value = false
            break;
        case 5:
            isActive1.value = false
            isActive2.value = true
            isActive3.value = false
            break;
        case 10:
        isActive1.value = false
            isActive2.value = false
            isActive3.value = true
            break;
    }
    queryParameters.status = status
    getTableData()
}
function resetQueryParam() {
    queryParameters.containerNo = ''
    queryParameters.orderNo = ''
    queryParameters.outDate = ''
    queryParameters.agentName = ''
    queryParameters.returnDate = ''
    queryParameters.rentStatus = ''
    getTableData()
}

const tableRef = ref({ multipleSelection: [] })
const toCollect = () => {
    let checkAllItem = []
    if(isSelectAll.value){
        checkAllItem = tableRef.value.multipleSelection
    }else{
        checkAllItem = allId.value
    }
    const ids = checkAllItem.map((item: any) => item.id)
    if (ids.length < 1) return ElMessage.warning('请选择要收取的箱号！')
    ElMessageBox.confirm('确认收取选中的集装箱？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        let reqParameters = {
            detailIds: ids
        }
        paymentBoxRentOrderDetentionCharge(reqParameters).then((res: any) => {
            if(res.code == "00000"){
                ElMessage.success('收取成功！')
                getTableData()
            }else{
                ElMessage.error(res.msg)
            }
        }).catch((error) => {
            ElMessage.error(error)
        })
    }).catch(() => {
        // ElMessage.warning('请选择要收取的箱号！')
    })
}
const exportExcel = () => {
    let checkAllItem = []
    if(isSelectAll.value){
        checkAllItem = tableRef.value.multipleSelection
    }else{
        checkAllItem = allId.value
    }
    const ids = checkAllItem.map((item: any) => item.id)
    if (ids.length < 1) return ElMessage.warning('请选择要导出的箱号！')
    ElMessageBox.confirm('确认要导出选中的集装箱？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        let reqParameters = {
            returnBoxListDetailIds: ids
        }
        exportBoxReturnBoxListDetail(reqParameters).then((res: any) => {
            downloadFile(res, '出租箱超期费')
          
        }).catch((error) => {
            ElMessage.error(error)
        })
    }).catch(() => {
        // ElMessage.warning('请选择要收取的箱号！')
    })
}
//分页
function onTablePageChange(page: { pageNum: number; pageSize: number }) {
  param.pageNum = page.pageNum;
  param.pageSize = page.pageSize;
  getTableData();
};

const isSelectAll = ref(true) // true:显示全选按钮  false：显示取消全选按钮
const allId = ref([]) // 使用全选功能时使用
const disableHeaderCheckbox = ref(false) // true:禁用表头全选/全取消 选择框 false:开启 表头全选/全取消 选择框
const isAllCheck = ref(false) //是否使用全选功能
const checkAll = ref([]) //点击全选按钮时 选中列表所有内容（包含当前页和所有后续页）
const slectAll = async(val:any) =>{
    checkAll.value = []
    await boxRentOrderDetentionChargePage({ pageNum:1,pageSize:10000}).then(res =>{ 
      if(res.code == "00000" && res.data.list  && res.data.total){
        isSelectAll.value = false
        disableHeaderCheckbox.value = true
        res.data.list.forEach(item => {
          checkAll.value.push(item)
        })
        isAllCheck.value = true
        allId.value = checkAll.value
        tableRef.value.checkAll()
      }else{
        ElMessage.error("全选失败，请刷新页面，或者手动选择")
      }
 })
}
const deselectAll = () =>{
  allId.value = []
  disableHeaderCheckbox.value = false
  tableRef.value.clearCheckAll()
  isSelectAll.value = true
}

const updateSelectAll = (val) => {
  allId.value = val
  // console.log("11111",allId.value)
}
</script>
<style lang="scss" scoped>
.cursor{
    cursor:pointer;
    text-align: center;
}

.select-style{
    color: #2158F3;
    border-bottom: 2px solid #2158F3;
}
</style>